<template>
  <div>
    <FormPanel ref="topFilter" :list="topFilterList" :isSubmitBtn="false"></FormPanel>
    <FilterTable
      ref="table"
      columnsRef="allocationInNewRef"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      :onSyncTableData="handleSyncTableData"
      :onCellChange="changeAmount"
      :dataSource="listTable"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="isShowAddPart = true" :disabled="isOld">新增配件</el-button>
        <UploadFile
          style="margin: 0 10px;"
          :initial-value="fileInitalValue"
          isOnlyButton
          :limit="20"
          type="primary"
          icon="el-icon-download"
          :disabled="isOld"
          :actionUrl="`${server.DMSCLOUD_PART}/basedata/ttSalesPart/importSalesPart`"
          @change="handleUploadChange"
          >导入</UploadFile
        >
        <el-button size="small" type="primary" :loading="exportModelLoading" @click="exportModel">导出模板</el-button>
      </template>
    </FilterTable>
    <BaseDialog title="对方经销商" :visible.sync="isShowSearchCustomer" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchCustomer :customerNo="kehuxuanze" @close="isShowSearchCustomer = false" @addCustomerCode="confirmSearchCustomer" />
    </BaseDialog>
    <BaseDialog title="新增配件" :visible.sync="isShowAddPart" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddPanel :customerNo="kehuxuanze" @close="isShowAddPart = false" @addPart="addPart" @dblclickPartInfo="dblclickPartInfo" />
    </BaseDialog>
    <BaseDialog title="调拨出库单选择" :visible.sync="isShowSearchOldAllcation" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchAllocatOut :customerNo="kehuxuanze" @close="isShowSearchOldAllcation = false" @addAllocatOut="confirmSearchAllocatOut" />
    </BaseDialog>
    <div class="btnWrap">
      <el-button @click="closeDrawer(1)">取 消</el-button>
      <el-button type="primary" @click="closeDrawer(2)">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction } from '@/utils';
import { getUser, getUserId, getOwnerCode } from '@/assets/js/auth';
import moment from 'moment';
import { exportSalesModel } from '@/api/part/partOut/partSales/index';
import SearchCustomer from './SearchCustomer';
import { queryAllocationOutItems, dealerInfoByAllInfo, byAllInfo } from '@/api/part/allocation';
import SearchAllocatOut from './searchAllocatOut';
import _ from 'lodash';
import AddPanel from './AddPanel';
import SERVER from '@/api/server';
import { getCangKuSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';
import { jsonToHump, exportExcelFile } from '@/utils/index';

export default {
  mixins: [dictionary],
  components: {
    SearchCustomer,
    AddPanel,
    SearchAllocatOut
  },
  data() {
    return {
      topFilterList: this.createTopFIlterList(),
      columns: this.createTableColumns(),
      isShowAddPart: false,
      fetchapi: () => {},
      exportModelLoading: false,
      kehuxuanze: '',
      rowData: {},
      listTable: [],
      server: SERVER,
      isShowSearchCustomer: false,
      fetchParams: { xhrAbort: true },
      fileInitalValue: [],
      isShowSearchOldAllcation: false,
      syncTableData: [], // 同步的table数据
      isOld: false
    };
  },
  mounted() {
    this.topFilterList.find(x => x.fieldName == 'handler').itemList = [{ text: getUser(), value: getUserId() }];
    this.getAllStorage();
  },
  methods: {
    addPart() {},
    delete(val) {
      this.$refs.table.EXECUTE_DELETE([val]);
    },
    dblclickPartInfo(val) {
      console.log(val);
      let obj = _.cloneDeep(val);
      jsonToHump(obj);
      delete obj.$index;
      obj.inPrice = obj.costPrice;
      obj.inAmount = obj.inPrice * obj.inQuantity;
      let flag = false;
      this.syncTableData.find(x => {
        if (x.partNo == obj.partNo && x.partType == obj.partType) {
          flag = true;
        }
      });
      if (flag) {
        this.$notify({
          title: '提示',
          message: '配件已存在',
          type: 'warning'
        });
        return;
      }
      this.$refs.table.EXECUTE_INSERT(obj);
      this.$notify({
        title: '提示',
        message: '配件已添加',
        type: 'success'
      });
    },
    async confirmSearchAllocatOut(row) {
      console.log(row, 'allocatOut');
      if (_.isNil(row.allocateOutNo)) {
        this.$notify({
          title: '提示',
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }
      this.topFilterList.find(x => x.fieldName == 'oldAllocateOutNo').initialValue = row.allocateOutNo;
      this.topFilterList.find(x => x.fieldName == 'customerCode').initialValue = row.customerName;
      this.rowData = { dealerCode: row.customerCode, dealerName: row.customerName };
      this.topFilterList.find(x => x.fieldName == 'customerCode').disabled = true;
      this.topFilterList.find(x => x.fieldName == 'oldAllocateOutNo').disabled = true;
      this.columns.find(x => x.dataIndex == 'inQuantity').disabled = true;
      this.isOld = true;
      let res = await queryAllocationOutItems({ allocateOutNo: row.allocateOutNo });
      if (res.resultCode == 200) {
        let obj = res.data;
        for (let i = 0; i < obj.length; i++) {
          obj[i].inPrice = obj[i].costPrice;
          obj[i].inQuantity = obj[i].outQuantity;
          obj[i].inAmount = obj[i].inPrice * obj[i].inQuantity;
          obj[i].itemId = null;
        }
        this.$refs.table.EXECUTE_INSERT(obj);
        this.$notify({
          title: '提示',
          message: '配件已添加',
          type: 'success'
        });
        this.topFilterList.find(x => x.fieldName == 'oldAllocateOutNo').disabled = true;
        this.isShowSearchOldAllcation = false;
      }
    },
    async confirmSearchCustomer(row) {
      console.log(row, 'rowCustomer');
      this.rowData = row[0];
      let ownerCode = await getOwnerCode();
      console.log('row[0].dealerCode', row[0].dealerCode);
      if (row && row[0].dealerCode != ownerCode) {
        this.topFilterList.find(x => x.fieldName == 'customerCode').initialValue = row[0].dealerName;
      }
    },
    async closeDrawer(val) {
      if (val == 1) {
        this.$emit('close', false);
      } else {
        let data = await this.$refs.topFilter.GET_FORM_DATA();
        let info = _.cloneDeep(data[1]);
        if (this.syncTableData.length <= 0) {
          this.$notify({
            title: '提示',
            message: ' 请添加配件',
            type: 'warning'
          });
          return;
        }
        info.allcationTable = this.syncTableData;
        info.customerCode = this.rowData.dealerCode;
        info.customerName = this.rowData.dealerName;
        let ownerCode = await getOwnerCode();
        console.log(info, 'info::');
        this.$emit('confirm', Object.assign({}, info));
        this.$emit('close', false);
      }
      this.isOld = false;
    },
    createTopFIlterList() {
      return [
        {
          type: 'INPUT',
          label: '入库单号',
          disabled: true,
          fieldName: 'allocateInNo'
        },
        {
          type: 'INPUT',
          label: '对方经销商',
          fieldName: 'customerCode',
          readonly: true,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.isShowSearchCustomer = true;
                }}
              ></el-button>
            );
          },
          onEnter: val => {
            console.log('对方经销商 onEnter');
            this.isShowSearchCustomer = true;
          },
          rules: [
            {
              required: true,
              message: '对方经销商必填',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '原单据号',
          fieldName: 'oldAllocateOutNo',
          readonly: true,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.isShowSearchOldAllcation = true;
                }}
              ></el-button>
            );
          },
          onEnter: val => {
            console.log('原单据号 onEnter');
            this.isShowSearchOldAllcation = true;
          }
        },
        {
          type: 'SELECT',
          label: '经办人',
          disabled: true,
          fieldName: 'handler',
          itemList: [],
          initialValue: getUserId(),
          rules: [
            {
              required: true,
              message: '经办人必填',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '经办人电话',
          fieldName: 'handlerPhone',
          rules: [
            {
              required: true,
              message: '经办人电话必填',
              trigger: 'change'
            },
            {
              pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
              message: '请填写正确的手机格式',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '申请日期',
          fieldName: 'orderDate',
          disabled: true,
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'TEXT_AREA',
          label: '申请备注',
          selfCols: '3',
          fieldName: 'remark'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.topFilterList.find(x => x.fieldName == 'oldAllocateOutNo').initialValue ? true : false} onClick={() => this.delete(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '仓库名称',
          dataIndex: 'storageCode',
          dictItems: [],
          sorter: true
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true
        },
        {
          title: '调拨数量',
          dataIndex: 'inQuantity',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number',
          min: 0,
          max: Infinity,
          widht: 130,
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '调拨单价',
          filterType: 'number',
          dataIndex: 'inPrice',
          precision: 2,
          sorter: true
        },
        {
          title: '调拨金额',
          filterType: 'number',
          precision: 2,
          dataIndex: 'inAmount',
          initialValue: 0,
          sorter: true
        }
      ];
    },
    changeAmount(val, row) {
      console.log('val::', val, 'row::', row);
      row.inAmount = val[Object.keys(val)[0]] * row.inPrice;
      console.log('val1::', val, 'row::1', row);
    },
    collapseHandle() {
      this.refs.table.EXECUTE_RESET_HEIGHT();
    },
    // 同步table数据
    handleSyncTableData(list) {
      this.syncTableData = list;
    },
    //导出模板
    exportModel() {
      this.exportModelLoading = true;
      exportSalesModel().then(res => {
        exportExcelFile(res.data, '调拨入库模板');
        this.exportModelLoading = false;
      });
    },
    // 订单导入成功事件
    handleUploadChange(e) {
      console.log('导入文件上传成功', e);
      if (e != 1) {
        this.fileInitalValue = e;
        let excelData = _.cloneDeep(e[e.length - 1].url.result);
        for (const item of this.listTable) {
          for (const items of excelData) {
            if (item.PART_NO == items.PART_NO && item.STORAGE_CODE == items.STORAGE_CODE) {
              item.PART_QUANTITY = Number(item.PART_QUANTITY) + Number(items.PART_QUANTITY);
            }
          }
          excelData = excelData.filter(items => {
            return items.PART_NO != item.PART_NO || item.STORAGE_CODE != items.STORAGE_CODE;
          });
        }
        console.log(excelData, 'excelData');
        this.handleDetailSelectConfirm(excelData, e[e.length - 1].url.errorList);
      }
    },
    handleDetailSelectConfirm(e, data) {
      let partList = e;

      // 校验重复配件
      let newPartArr = [],
        repeatingPartArr = []; // 重复配件，新配件
      partList.map(item => {
        let a = this.syncTableData.find(x => x.partNo == item.PART_NO);
        if (a) {
          repeatingPartArr.push(item);
        } else {
          newPartArr.push(item);
        }
      });
      if (repeatingPartArr.length) {
        let idsArr = repeatingPartArr.map(item => item.PART_NO);
        notifyAction('此订单类型禁止添加重复配件，配件代码：' + idsArr.join(','), 'warning');
        return;
      }

      newPartArr = JSON.parse(JSON.stringify(newPartArr)); // 浅拷贝防止原始数据修改
      this.formatPartsData(newPartArr);
      newPartArr.map(x => {
        x.inPrice = x.partCostPrice;
        x.inQuantity = x.partQuantity;
      });
      this.$refs.table.EXECUTE_INSERT(newPartArr);
      if (data.length > 0) {
        let errorData = data.map(x => {
          if (x.result === '查询不到库存') {
            return '仓库：' + x.storageCode + '中配件：' + x.partNo + '不存在';
          } else {
            return x.partNo + '配件调拨数量为负';
          }
        });
        this.$notify.warning({ title: '提示信息', message: `导入成功，${errorData.join('，')}，请确认模板` });
      } else {
        notifyAction('配件导入成功', 'success');
      }
      // this.partDetailIdList = partList.map(item => item.partNo);
    },
    async getAllStorage() {
      let res = await getCangKuSelect({
        // type: this.type == 'add' ? 0 : '', // 0是非oem 0是oem  EP-23605 去除入库oem类型限制
        // ptype: this.ptype ? this.ptype : null // ,模块区分
      });
      let storageData = res.data.map(item => ({ text: item.STORAGE_NAME, value: item.STORAGE_CODE }));
      this.columns.find(item => item.dataIndex == 'storageCode').dictItems = storageData;
    },
    formatPartsData(arr) {
      jsonToHump(arr);
    }
  }
};
</script>

<style lang="less" scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
